package liumengbaio.lolzhangyoubao.Activity.Activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.io.File;

import liumengbaio.lolzhangyoubao.Activity.View.BottomPopwindow;
import liumengbaio.lolzhangyoubao.Activity.View.CustomDialog;
import liumengbaio.lolzhangyoubao.Activity.View.CustomDialogBirth;
import liumengbaio.lolzhangyoubao.Activity.View.CustomDialogBlackVoice;
import liumengbaio.lolzhangyoubao.Activity.View.CustomDialogGoodSize;
import liumengbaio.lolzhangyoubao.Activity.View.CustomDialogUserHero;
import liumengbaio.lolzhangyoubao.Activity.View.SaveDialog;
import liumengbaio.lolzhangyoubao.Activity.utils.HttpUtils;
import liumengbaio.lolzhangyoubao.R;

public class EditActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int NONE = 0;
    private static final int PHOTO_GRAPH = 1;// 拍照
    private static final int PHOTO_ZOOM = 2; // 缩放
    private static final int PHOTO_RESOULT = 3;// 结果
    private static final String IMAGE_UNSPECIFIED = "image/*";
    private LinearLayout line_image;
    private RelativeLayout relative_QQ, relative_BIRTH, city_relative, person_singnal, bind_role,
            good_side, doBlack_voice, long_use_hero,load_info;
    private ImageView edit_head_icon;
    private boolean flag;
    private SharedPreferences sp, mysp;
    private SharedPreferences.Editor editor;
    private BottomPopwindow bottomPopwindow;
    private TextView QQ_number, birthday, city, tv_singnal,
            edit_good_side, balck_voice, tv_user_hero, tv_sex,
            edit_area, LOL_name,
            tv_zhangyoubao_name;
    private String Date;
    private Button edit_head_left_title, btn_save;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
        EventBus.getDefault().register(this);
        sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        mysp = getSharedPreferences("myInfo", MODE_PRIVATE);
        editor = mysp.edit();
        initView();
        initData();
    }

    private void initData() {
        edit_head_left_title.setOnClickListener(this);
        good_side.setOnClickListener(this);
        line_image.setOnClickListener(this);
        doBlack_voice.setOnClickListener(this);
        long_use_hero.setOnClickListener(this);
        bind_role.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        person_singnal.setOnClickListener(this);
        relative_BIRTH.setOnClickListener(this);
        city_relative.setOnClickListener(this);
        relative_QQ.setOnClickListener(this);
    }

    private void initView() {
        edit_head_left_title = (Button) findViewById(R.id.edit_head_left_title);
        balck_voice = (TextView) findViewById(R.id.balck_voice);
        tv_user_hero = (TextView) findViewById(R.id.tv_user_hero);
        tv_sex = (TextView) findViewById(R.id.tv_sex);
        btn_save = (Button) findViewById(R.id.btn_save);
        load_info= (RelativeLayout) findViewById(R.id.load_info);
        edit_area = (TextView) findViewById(R.id.edit_area);
        LOL_name = (TextView) findViewById(R.id.LOL_name);
        QQ_number = (TextView) findViewById(R.id.QQ_number);
        tv_zhangyoubao_name = (TextView) findViewById(R.id.tv_zhangyoubao_name);
        birthday = (TextView) findViewById(R.id.birthday);
        city = (TextView) findViewById(R.id.city);
        tv_singnal = (TextView) findViewById(R.id.tv_singnal);
        line_image = (LinearLayout) findViewById(R.id.line_image);
        relative_QQ = (RelativeLayout) findViewById(R.id.relative_QQ);
        doBlack_voice = (RelativeLayout) findViewById(R.id.doBlack_voice);
        bind_role = (RelativeLayout) findViewById(R.id.bind_role);
        edit_good_side = (TextView) findViewById(R.id.edit_good_side);
        good_side = (RelativeLayout) findViewById(R.id.good_side);
        long_use_hero = (RelativeLayout) findViewById(R.id.long_use_hero);
        city_relative = (RelativeLayout) findViewById(R.id.city_relative);
        relative_BIRTH = (RelativeLayout) findViewById(R.id.relative_BIRTH);
        person_singnal = (RelativeLayout) findViewById(R.id.person_singnal);
        bottomPopwindow = new BottomPopwindow(EditActivity.this, popWindowClick);
        edit_head_icon = (ImageView) findViewById(R.id.edit_head_icon);
        flag = sp.getBoolean("flag", false);
        if (flag)
            Picasso.with(EditActivity.this).load(sp.getString("headIcon", "")).into(edit_head_icon);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            popDialog();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        city.setText(sp.getString("selectCity", ""));
    }

    private void popDialog() {
        final SaveDialog.Builder buider = new SaveDialog.Builder(this);
        buider.setTitle("提示");
        //        buider.setMessage(QQ_number.getText().toString());
        buider.setPositiveButton("退出", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();

            }
        });

        buider.setNegativeButton("保存",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //在此进行资料保存，与底部大Button功能一样
                        save_personInfo();
                        dialog.dismiss();
                    }
                });

        buider.create().show();
    }

    private View.OnClickListener popWindowClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    take_photo();
                    bottomPopwindow.dismiss();
                    break;
                case R.id.btn_pick_photo:
                    Intent album = new Intent(Intent.ACTION_GET_CONTENT);
                    album.setType("image/*");
                    startActivityForResult(album, PHOTO_ZOOM);
                    bottomPopwindow.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.line_image:
                bottomPopwindow.showAtLocation(EditActivity.this.findViewById(R.id.scrollView), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.relative_QQ:
                dialog_operation();
                break;
            case R.id.relative_BIRTH:
                DateDialog();
                break;
            case R.id.city_relative:
                Intent city_intent = new Intent(EditActivity.this, CityActivity.class);
                startActivity(city_intent);
                break;
            case R.id.person_singnal:
                signal_dialog();
                break;
            case R.id.edit_head_left_title:
                finish();
                break;
            case R.id.bind_role:
                Intent bind_role_intent = new Intent(EditActivity.this, BindRoleActivity.class);
                startActivity(bind_role_intent);
                break;
            case R.id.good_side:
                setGood_side();
                break;
            case R.id.doBlack_voice:
                setDoBlack_voice();
                break;
            case R.id.long_use_hero:
                setLong_use_hero();
                break;
            case R.id.btn_save:
                save_personInfo();
                break;
        }
    }

    private void signal_dialog() {
        final CustomDialog.Builder builder_signal = new CustomDialog.Builder(this);
        builder_signal.setTitle("输入个性签名");
        builder_signal.setMessage(tv_singnal.getText().toString());
        builder_signal.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });

        builder_signal.setNegativeButton("确认",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        tv_singnal.setText(builder_signal.getMessage());
                        dialog.dismiss();
                    }
                });

        builder_signal.create().show();

    }


    //调用系统相机
    private void take_photo() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
                .getExternalStorageDirectory(), "temp.jpg")));
        startActivityForResult(intent, PHOTO_GRAPH);
    }

    //裁剪方法
    private void take_catch(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面,
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");//进行修剪
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 500);
        intent.putExtra("outputY", 500);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_RESOULT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == NONE)
            return;
        // 拍照
        if (requestCode == PHOTO_GRAPH) {
            // 设置文件保存路径
            File picture = new File(Environment.getExternalStorageDirectory()
                    + "/temp.jpg");
            take_catch(Uri.fromFile(picture));
        }

        if (data == null)
            return;

        // 读取相册缩放图片
        if (requestCode == PHOTO_ZOOM) {
            take_catch(data.getData());
        }
        // 处理结果
        if (requestCode == PHOTO_RESOULT) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0-100)压缩文件
                //此处可以把Bitmap保存到sd卡中，具体请看：http://www.cnblogs.com/linjiqin/archive/2011/12/28/2304940.html
                edit_head_icon.setImageBitmap(photo); //把图片显示在ImageView控件上
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void save_personInfo() {
        String sp_name = tv_zhangyoubao_name.getText().toString();
        String sp_sex = tv_sex.getText().toString();
        String sp_qq = QQ_number.getText().toString();
        String sp_birth = birthday.getText().toString();
        String sp_city = city.getText().toString();
        String sp_singnal = tv_singnal.getText().toString();
        String sp_edit_area = edit_area.getText().toString();
        String sp_LOL_name = LOL_name.getText().toString();
        String sp_good_side = edit_good_side.getText().toString();
        String sp_doblack_voice = balck_voice.getText().toString();
        String sp_user_hero = tv_user_hero.getText().toString();
        if (sp_name.equals(mysp.getString("sp_name", "")) && sp_sex.equals(mysp.getString("sp_sex", ""))
                && sp_qq.equals(mysp.getString("sp_qq", "")) && sp_birth.equals(mysp.getString("sp_birth", ""))
                && sp_city.equals(mysp.getString("sp_city", "")) && sp_singnal.equals(mysp.getString("sp_singnal", ""))
                && sp_edit_area.equals(mysp.getString("sp_edit_area", "")) && sp_LOL_name.equals(mysp.getString("sp_LOL_name", ""))
                && sp_good_side.equals(mysp.getString("sp_good_side", "")) && sp_doblack_voice.equals(mysp.getString("sp_doblack_voice", ""))
                && sp_user_hero.equals(mysp.getString("sp_user_hero", ""))) {
            Toast.makeText(this, "if", Toast.LENGTH_SHORT).show();
            Log.i("002",sp_name+sp_sex+sp_qq+sp_birth+sp_city+sp_singnal+sp_edit_area+sp_LOL_name+sp_good_side);
            Log.i("002",mysp.getString("sp_name","")+mysp.getString("sp_sex","")+mysp.getString("sp_qq","")
                    +mysp.getString("sp_birth",""));
            return;
        } else {
            editor.putString("sp_name", sp_name);
            editor.putString("sp_sex", sp_sex);
            editor.putString("sp_qq", sp_qq);
            editor.putString("sp_birth", sp_birth);
            editor.putString("sp_city", sp_city);
            editor.putString("sp_singnal", sp_singnal);
            editor.putString("sp_edit_area", sp_edit_area);
            editor.putString("sp_LOL_name", sp_LOL_name);
            editor.putString("sp_good_side", sp_good_side);
            editor.putString("sp_doblack_voice", sp_doblack_voice);
            editor.putString("sp_user_hero", sp_user_hero);
            String url = "http://lol.zhangyoubao.com/apis/rest/UsersService/setUserInfo?&user" +
                    "id=15863305&token=1285c08b612411d0bfc35f213eb5d92a73&i_=aYD1xdXv2oJ" +
                    "YCUOsnL/LO1/nl4LDc5EUB0SHenAJb9E=&deviceId=aYD1xdXv2oJYCUOsnL/LO1/n" +
                    "l4LDc5EUB0SHenAJb9E=&t_=1473150230951&p_" +
                    "=5198&v_=400901&a_=lol&pkg_=com.anzogame.lol&d_=android&osv_=1" +
                    "7&cha=youyiMartket&u_=15863305&modle_=vivo%20Y15T";
            String parmas = "nonce=753692&platform=Android&user_lol_info%5Brank%5D=1&use" +
                    "r_lol_info%5Benable_voice%5D=2&secretVersion=v1.0&secretId=AKIDz8kr" +
                    "bsJ5yKBZQpn74WFkmLPx3gnPhESA&user_lol_info%5Bicon%5D=http%3A%2F%2Fcd" +
                    "n.tgp.qq.com%2Fpallas%2Fimages%2Fusericon%2F684.png&game=lol&osVersi" +
                    "on=17&birth=1994-03-14&deviceId=aYD1xdXv2oJYCUOsnL%2FLO1%2Fnl4LDc5EU" +
                    "B0SHenAJb9E%3D&os=Android&signature=" + sp_singnal + "&user_lol_inf" +
                    "o%5Bfield%5D=" + sp_good_side + "&platformVersion=400901&user_lo" +
                    "l_info%5Btier%5D=5&gps=&sign=&secretSignature=SD9WMtUQ6sORd2CKH2D" +
                    "RmdUOcbY%3D&sex=1&time=1473150230&apiVersion=v1&user_lol_info%5Bgo" +
                    "od_at%5D=" + sp_user_hero + "&city=sp_city&qq=" + sp_qq;
            try {
                HttpUtils.doPostAsyn(url, parmas, new HttpUtils.CallBack() {
                    @Override
                    public void onRequestComplete(String result) {

                    }
                }, handler);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*
     *自定义dialog的使用
     */
    private void dialog_operation() {
        final CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setTitle("输入QQ号");
        builder.setMessage(QQ_number.getText().toString());
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });

        builder.setNegativeButton("确认",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        QQ_number.setText(builder.getMessage());
                        dialog.dismiss();
                    }
                });

        builder.create().show();

    }

    private void DateDialog() {
        final CustomDialogBirth.Builder builder = new CustomDialogBirth.Builder(this);
        builder.setTitle("生日日期");
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setNegativeButton("确认",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        birthday.setText(Date);
                        dialog.dismiss();
                    }
                });

        builder.create().show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void haha(String date) {
        Date = date;
    }

    private void setGood_side() {
        final CustomDialogGoodSize.Builder builder_signal_good = new CustomDialogGoodSize.Builder(this);
        builder_signal_good.setTitle("设置擅长位置");
        builder_signal_good.setMessage(" ");
        builder_signal_good.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });

        builder_signal_good.setNegativeButton("确认",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        edit_good_side.setText(builder_signal_good.getMessage());
                        dialog.dismiss();
                    }
                });

        builder_signal_good.create().show();

    }

    private void setDoBlack_voice() {
        final CustomDialogBlackVoice.Builder builder_signal_balck_voice = new CustomDialogBlackVoice.Builder(this);
        builder_signal_balck_voice.setTitle("设置游戏开黑语音");
        builder_signal_balck_voice.setMessage("愿意");
        builder_signal_balck_voice.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });

        builder_signal_balck_voice.setNegativeButton("取消",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        balck_voice.setText(builder_signal_balck_voice.getMessage());
                        dialog.dismiss();
                    }
                });

        builder_signal_balck_voice.create().show();
    }

    private void setLong_use_hero() {
        final CustomDialogUserHero.Builder builder_user_hero = new CustomDialogUserHero.Builder(this);
        builder_user_hero.setTitle("输入常用英雄");
        builder_user_hero.setMessage(" ");
        builder_user_hero.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

            }
        });

        builder_user_hero.setNegativeButton("确认",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        tv_user_hero.setText(builder_user_hero.getMessage());
                        dialog.dismiss();
                    }
                });

        builder_user_hero.create().show();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                load_info.setVisibility(View.VISIBLE);
                Handler handler1=new Handler();
                handler1.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(EditActivity.this, "资料保存成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                },1000);
            } else {
                Toast.makeText(EditActivity.this, "网络出现问题", Toast.LENGTH_SHORT).show();
            }
        }
    };
}
